<template>
  <a-form ref="formStep2Ref" :model="form.formStep2" layout="vertical" :rules="rulesStep2" v-bind="layout">
    <a-collapse :default-active-key="activeKeys">
      <template #expandIcon="{ isActive }">
        <caret-right-outlined :rotate="isActive ? 90 : 0" />
      </template>
      <a-collapse-panel key="1" header="基本信息3">
        <a-row :gutter="16">
          <a-col v-bind="colLayout.cols">
            <a-form-item name="demoNotnull" label="必填" has-feedback>
              <a-input v-model:value="form.formStep2.demoNotnull" :maxlength="50" placeholder="请输入必填" />
            </a-form-item>
          </a-col>
          <a-col v-bind="colLayout.cols2">
            <a-form-item name="demoTextarea" label="多行文本">
              <a-textarea v-model:value="form.formStep2.demoTextarea" :rows="2" :maxlength="4000" placeholder="请输入多行文本" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col v-bind="colLayout.cols">
            <a-form-item name="demoCode" label="编码">
              <a-input v-model:value="form.formStep2.demoCode" disabled />
            </a-form-item>
          </a-col>
          <a-col v-bind="colLayout.cols">
            <a-form-item name="demoPhone" label="电话(正则)">
              <a-input v-model:value="form.formStep2.demoPhone" :maxlength="50" placeholder="请输入电话(正则)" />
            </a-form-item>
          </a-col>
          <a-col v-bind="colLayout.cols">
            <a-form-item name="demoEmail" label="邮箱(正则)">
              <a-input v-model:value="form.formStep2.demoEmail" :maxlength="50" placeholder="请输入邮箱(正则)" />
            </a-form-item>
          </a-col>
          <a-col v-bind="colLayout.cols">
            <a-form-item name="demoWebsite" label="网址(正则)">
              <a-input v-model:value="form.formStep2.demoWebsite" :maxlength="50" placeholder="请输入网址(正则)" />
            </a-form-item>
          </a-col>
        </a-row>
      </a-collapse-panel>
      <a-collapse-panel key="2" header="基本信息4">
        <a-row :gutter="16">
          <a-col v-bind="colLayout.cols2">
            <a-form-item label="主子表嵌套示例-子表">
              <!-- 子表组件 -->
              <AvicTable
                ref="demoSubNest"
                table-key="demoSubNest"
                :height="300"
                :columns="columns"
                :row-key="(record) => record.id"
                :data-source="list"
                :loading="subLoading"
                :row-selection="{
                  selectedRowKeys: selectedRowKeys,
                  onChange: onSelectChange,
                  columnWidth: 40,
                  fixed: true
                }"
                :show-table-setting="false"
                :page-parameter="queryParam.pageParameter"
                :total="totalPage"
                :custom-row="customRow"
                @change="handleTableChange"
              >
                <template #toolBarLeft>
                  <a-space>
                    <a-space>
                      <a-button title="添加" type="primary" @click="handleAdd">
                        <template #icon>
                          <plus-outlined />
                        </template>
                        添加
                      </a-button>
                      <a-button
                        title="删除"
                        danger
                        :type="selectedRowKeys.length == 0 ? 'default' : 'primary'"
                        :loading="delLoading"
                        @click="handleDelete(selectedRowKeys, '')"
                      >
                        <template #icon>
                          <delete-outlined />
                        </template>
                        删除
                      </a-button>
                    </a-space>
                  </a-space>
                </template>
                <template #bodyCell="{ column, text, record }">
                  <AvicRowEdit
                    v-if="
                      [
                        'demoPhone',
                        'demoText2',
                        'demoRichtext',
                        'demoSwitch',
                        'demoCode',
                        'demoEmail',
                        'demoUnique',
                        'demoBackgroundColor',
                        'demoNotnull',
                        'demoWebsite'
                      ].includes(column.dataIndex)
                    "
                    :record="record"
                    :column="column.dataIndex"
                  >
                    <template #edit>
                      <a-input
                        v-model:value="record[column.dataIndex]"
                        :maxlength="200"
                        style="width: 100%"
                        placeholder="请输入"
                        @input="$forceUpdate()"
                        @blur="blurInput($event, record, column.dataIndex)"
                      />
                    </template>
                  </AvicRowEdit>
                  <AvicRowEdit v-else-if="column.dataIndex === 'demoPositionId'" :record="record" :column="column.dataIndex">
                    <template #edit>
                      <AvicCommonSelect
                        v-model:value="record.demoPositionId"
                        :default-show-value="record.demoPositionIdAlias"
                        placeholder="请选择岗位"
                        type="positionSelect"
                        @callback="
                          (value, _selectRows) => {
                            changeCommonSelect(value, record, 'demoPositionId');
                          }
                        "
                      />
                    </template>
                    <template #default>
                      <span :title="record['demoPositionIdAlias']">{{ record['demoPositionIdAlias'] }}</span>
                    </template>
                  </AvicRowEdit>
                  <AvicRowEdit v-else-if="column.dataIndex === 'demoDate'" :record="record" :column="column.dataIndex">
                    <template #edit>
                      <a-date-picker v-model:value="record.demoDate" value-format="YYYY-MM-DD" placeholder="请选择日期" />
                    </template>
                  </AvicRowEdit>
                  <AvicRowEdit v-else-if="column.dataIndex === 'demoRoleId'" :record="record" :column="column.dataIndex">
                    <template #edit>
                      <AvicCommonSelect
                        v-model:value="record.demoRoleId"
                        :default-show-value="record.demoRoleIdAlias"
                        placeholder="请选择角色"
                        type="roleSelect"
                        @callback="
                          (value, _selectRows) => {
                            changeCommonSelect(value, record, 'demoRoleId');
                          }
                        "
                      />
                    </template>
                    <template #default>
                      <span :title="record['demoRoleIdAlias']">{{ record['demoRoleIdAlias'] }}</span>
                    </template>
                  </AvicRowEdit>
                  <AvicRowEdit v-else-if="column.dataIndex === 'demoGroupId'" :record="record" :column="column.dataIndex">
                    <template #edit>
                      <AvicCommonSelect
                        v-model:value="record.demoGroupId"
                        :default-show-value="record.demoGroupIdAlias"
                        placeholder="请选择群组"
                        type="groupSelect"
                        @callback="
                          (value, _selectRows) => {
                            changeCommonSelect(value, record, 'demoGroupId');
                          }
                        "
                      />
                    </template>
                    <template #default>
                      <span :title="record['demoGroupIdAlias']">{{ record['demoGroupIdAlias'] }}</span>
                    </template>
                  </AvicRowEdit>
                  <AvicRowEdit v-else-if="column.dataIndex === 'secretLevel'" :record="record" :column="column.dataIndex">
                    <template #edit>
                      <a-select
                        v-model:value="record.secretLevel"
                        style="width: 100%"
                        placeholder="请选择密级"
                        @change="
                          (value) =>
                            changeControlValue({ value, record, column: 'secretLevel', lookupList: lookupList?.PLATFORM_FILE_SECRET_LEVEL })
                        "
                      >
                        <a-select-option
                          v-for="select in lookupList?.PLATFORM_FILE_SECRET_LEVEL"
                          :key="select.sysLookupTlId"
                          :value="select.lookupCode"
                          :title="select.lookupName"
                          :disabled="select.disabled === true"
                        >
                          {{ select.lookupName }}
                        </a-select-option>
                      </a-select>
                    </template>
                    <template #default>
                      <span :title="record['secretLevelName']">{{ record['secretLevelName'] }}</span>
                    </template>
                  </AvicRowEdit>
                  <AvicRowEdit v-else-if="column.dataIndex === 'demoCheckbox'" :record="record" :column="column.dataIndex">
                    <template #edit>
                      <a-checkbox-group
                        v-model:value="record.demoCheckbox"
                        button-style="solid"
                        @change="
                          (value) => {
                            changeControlValue({
                              value,
                              record,
                              column: 'demoCheckbox',
                              lookupList: lookupList?.PLATFORM_CHECK_TYPE
                            });
                          }
                        "
                      >
                        <a-checkbox
                          v-for="item in lookupList?.PLATFORM_CHECK_TYPE"
                          :key="item.sysLookupTlId"
                          :value="item.lookupCode"
                          :disabled="item.disabled === true"
                        >
                          {{ item.lookupName }}
                        </a-checkbox>
                      </a-checkbox-group>
                    </template>
                    <template #default>
                      <span :title="record['demoCheckboxName']">{{ record['demoCheckboxName'] }}</span>
                    </template>
                  </AvicRowEdit>
                  <AvicRowEdit v-else-if="column.dataIndex === 'demoDeptId'" :record="record" :column="column.dataIndex">
                    <template #edit>
                      <AvicCommonSelect
                        v-model:value="record.demoDeptId"
                        :default-show-value="record.demoDeptIdAlias"
                        placeholder="请选择部门"
                        type="deptSelect"
                        @callback="
                          (value, _selectRows) => {
                            changeCommonSelect(value, record, 'demoDeptId');
                          }
                        "
                      />
                    </template>
                    <template #default>
                      <span :title="record['demoDeptIdAlias']">{{ record['demoDeptIdAlias'] }}</span>
                    </template>
                  </AvicRowEdit>
                  <AvicRowEdit v-else-if="column.dataIndex === 'demoInteger'" :record="record" :column="column.dataIndex">
                    <template #edit>
                      <a-input-number
                        v-model:value="record.demoInteger"
                        :min="0"
                        :max="999999999"
                        :precision="0"
                        :step="1"
                        style="width: 100%"
                        placeholder="请输入整数"
                      />
                    </template>
                  </AvicRowEdit>
                  <AvicRowEdit v-else-if="column.dataIndex === 'demoUserId'" :record="record" :column="column.dataIndex">
                    <template #edit>
                      <AvicCommonSelect
                        v-model:value="record.demoUserId"
                        :default-show-value="record.demoUserIdAlias"
                        placeholder="请选择用户"
                        type="userSelect"
                        @callback="
                          (value, _selectRows) => {
                            changeCommonSelect(value, record, 'demoUserId');
                          }
                        "
                      />
                    </template>
                    <template #default>
                      <span :title="record['demoUserIdAlias']">{{ record['demoUserIdAlias'] }}</span>
                    </template>
                  </AvicRowEdit>
                  <AvicRowEdit v-else-if="column.dataIndex === 'demoSelectMultiple'" :record="record" :column="column.dataIndex">
                    <template #edit>
                      <a-select
                        v-model:value="record.demoSelectMultiple"
                        mode="multiple"
                        style="width: 100%"
                        placeholder="请选择下拉多选"
                        @change="
                          (value) =>
                            changeControlValue({
                              value,
                              record,
                              column: 'demoSelectMultiple',
                              lookupList: lookupList?.PLATFORM_CHECK_TYPE
                            })
                        "
                      >
                        <a-select-option
                          v-for="select in lookupList?.PLATFORM_CHECK_TYPE"
                          :key="select.sysLookupTlId"
                          :value="select.lookupCode"
                          :title="select.lookupName"
                          :disabled="select.disabled === true"
                        >
                          {{ select.lookupName }}
                        </a-select-option>
                      </a-select>
                    </template>
                    <template #default>
                      <span :title="record['demoSelectMultipleName']">{{ record['demoSelectMultipleName'] }}</span>
                    </template>
                  </AvicRowEdit>
                  <AvicRowEdit v-else-if="column.dataIndex === 'demoTextarea'" :record="record" :column="column.dataIndex">
                    <template #edit>
                      <a-textarea v-model:value="record.demoTextarea" :maxlength="4000" placeholder="请输入多行文本" />
                    </template>
                  </AvicRowEdit>
                  <AvicRowEdit v-else-if="column.dataIndex === 'demoRadio'" :record="record" :column="column.dataIndex">
                    <template #edit>
                      <a-radio-group
                        v-model:value="record.demoRadio"
                        @change="
                          ({ target: { value } }) => {
                            changeControlValue({ value, record, column: 'demoRadio', lookupList: lookupList?.PLATFORM_SEX });
                          }
                        "
                      >
                        <a-radio
                          v-for="item in lookupList?.PLATFORM_SEX"
                          :key="item.sysLookupTlId"
                          :value="item.lookupCode"
                          :disabled="item.disabled === true"
                        >
                          {{ item.lookupName }}
                        </a-radio>
                      </a-radio-group>
                    </template>
                    <template #default>
                      <span :title="record['demoRadioName']">{{ record['demoRadioName'] }}</span>
                    </template>
                  </AvicRowEdit>
                  <AvicRowEdit v-else-if="column.dataIndex === 'demoModalSelect'" :record="record" :column="column.dataIndex">
                    <template #edit>
                      <AvicModalSelect
                        v-model:value="record.demoModalSelect"
                        modal-title="选择弹窗"
                        placeholder="请选择弹窗"
                        value-field="demoNotnull"
                        show-field="demoNotnull"
                        :default-show-value="record.demoModalSelectAlias"
                        :select-component="demoSingleSelectComponent"
                        :allow-clear="true"
                        :is-multi-selection="false"
                      />
                    </template>
                  </AvicRowEdit>
                  <AvicRowEdit v-else-if="column.dataIndex === 'demoDateTime'" :record="record" :column="column.dataIndex">
                    <template #edit>
                      <a-date-picker v-model:value="record.demoDateTime" value-format="YYYY-MM-DD" placeholder="请选择日期时间" />
                    </template>
                  </AvicRowEdit>
                  <AvicRowEdit v-else-if="column.dataIndex === 'demoNumber'" :record="record" :column="column.dataIndex">
                    <template #edit>
                      <a-input-number
                        v-model:value="record.demoNumber"
                        :min="0"
                        :max="9999999999.99"
                        :precision="2"
                        :step="0.01"
                        style="width: 100%"
                        placeholder="请输入小数"
                      />
                    </template>
                    <template #default>
                      {{ proxy.$formatZero(text, 2) }}
                    </template>
                  </AvicRowEdit>
                  <AvicRowEdit v-else-if="column.dataIndex === 'demoSelect'" :record="record" :column="column.dataIndex">
                    <template #edit>
                      <a-select
                        v-model:value="record.demoSelect"
                        style="width: 100%"
                        placeholder="请选择下拉"
                        @change="
                          (value) => changeControlValue({ value, record, column: 'demoSelect', lookupList: lookupList?.PLATFORM_DEGREE })
                        "
                      >
                        <a-select-option
                          v-for="select in lookupList?.PLATFORM_DEGREE"
                          :key="select.sysLookupTlId"
                          :value="select.lookupCode"
                          :title="select.lookupName"
                          :disabled="select.disabled === true"
                        >
                          {{ select.lookupName }}
                        </a-select-option>
                      </a-select>
                    </template>
                    <template #default>
                      <span :title="record['demoSelectName']">{{ record['demoSelectName'] }}</span>
                    </template>
                  </AvicRowEdit>
                  <AvicRowEdit v-else-if="column.dataIndex === 'demoRadioButton'" :record="record" :column="column.dataIndex">
                    <template #edit>
                      <a-radio-group
                        v-model:value="record.demoRadioButton"
                        button-style="solid"
                        @change="
                          ({ target: { value } }) => {
                            changeControlValue({
                              value,
                              record,
                              column: 'demoRadioButton',
                              lookupList: lookupList?.PLATFORM_CHECK_TYPE
                            });
                          }
                        "
                      >
                        <a-radio-button
                          v-for="item in lookupList?.PLATFORM_CHECK_TYPE"
                          :key="item.sysLookupTlId"
                          :value="item.lookupCode"
                          :disabled="item.disabled === true"
                        >
                          {{ item.lookupName }}
                        </a-radio-button>
                      </a-radio-group>
                    </template>
                    <template #default>
                      <span :title="record['demoRadioButtonName']">{{ record['demoRadioButtonName'] }}</span>
                    </template>
                  </AvicRowEdit>
                  <template v-else-if="column.dataIndex === 'action'">
                    <a-button
                      class="inner-btn"
                      type="link"
                      @click="
                        (event) => {
                          handleDelete([record.id], event);
                        }
                      "
                    >
                      删除
                    </a-button>
                  </template>
                </template>
              </AvicTable>
            </a-form-item>
          </a-col>
        </a-row>
      </a-collapse-panel>
    </a-collapse>
  </a-form>
</template>
<script lang="ts" setup>
import { useLookup } from '@/utils/hooks/useLookup';
import { useDemoMainNestForm, emits } from './ts/DemoMainNestForm'; // 引入表单ts

const props = defineProps({
  formId: {
    type: String,
    default: ''
  },
  form: {
    type: Object,
    default: null
  }
});
const emit = defineEmits(emits);
const activeKeys = ['1', '2'];
const { proxy, formStep2Ref, rulesStep2, layout, colLayout, autoCode } = useDemoMainNestForm({
  props,
  emit
});

// 以下为子表操作逻辑
import type { DemoSubNestDto } from '@/api/avic/demo/DemoSubNestApi'; // 引入模块DTO
import { listDemoSubNestByPage } from '@/api/avic/demo/DemoSubNestApi'; // 引入模块API
import demoSingleSelect from '@/views/avic/demo/demosingle/DemoSingleSelect.vue'; // 引入弹窗选择页

const demoSingleSelectComponent = demoSingleSelect; // 自定义选择
const columns = [
  {
    title: '用户',
    dataIndex: 'demoUserId',
    key: 'demoUserId',
    ellipsis: true,
    minWidth: 120,
    resizable: true,
    customHeaderCell() {
      return {
        ['class']: 'required-table-title'
      };
    },
    align: 'left'
  },
  {
    title: '部门',
    dataIndex: 'demoDeptId',
    key: 'demoDeptId',
    ellipsis: true,
    minWidth: 120,
    resizable: true,
    align: 'left'
  },
  {
    title: '角色',
    dataIndex: 'demoRoleId',
    key: 'demoRoleId',
    ellipsis: true,
    minWidth: 120,
    resizable: true,
    align: 'left'
  },
  {
    title: '群组',
    dataIndex: 'demoGroupId',
    key: 'demoGroupId',
    ellipsis: true,
    minWidth: 120,
    resizable: true,
    align: 'left'
  },
  {
    title: '岗位',
    dataIndex: 'demoPositionId',
    key: 'demoPositionId',
    ellipsis: true,
    minWidth: 120,
    resizable: true,
    align: 'left'
  },
  {
    title: '单选',
    dataIndex: 'demoRadio',
    key: 'demoRadio',
    ellipsis: true,
    minWidth: 120,
    resizable: true,
    align: 'center'
  },
  {
    title: '单选（按钮）',
    dataIndex: 'demoRadioButton',
    key: 'demoRadioButton',
    ellipsis: true,
    minWidth: 120,
    resizable: true,
    align: 'center'
  },
  {
    title: '复选',
    dataIndex: 'demoCheckbox',
    key: 'demoCheckbox',
    ellipsis: true,
    minWidth: 120,
    resizable: true,
    align: 'left'
  },
  {
    title: '下拉',
    dataIndex: 'demoSelect',
    key: 'demoSelect',
    ellipsis: true,
    minWidth: 120,
    resizable: true,
    align: 'center'
  },
  {
    title: '下拉多选',
    dataIndex: 'demoSelectMultiple',
    key: 'demoSelectMultiple',
    ellipsis: true,
    minWidth: 120,
    resizable: true,
    align: 'left'
  },
  {
    title: '密级',
    dataIndex: 'secretLevel',
    key: 'secretLevel',
    ellipsis: true,
    minWidth: 120,
    resizable: true,
    customHeaderCell() {
      return {
        ['class']: 'required-table-title'
      };
    },
    align: 'center'
  },
  {
    title: '开关',
    dataIndex: 'demoSwitch',
    key: 'demoSwitch',
    ellipsis: true,
    minWidth: 120,
    resizable: true,
    align: 'left'
  },
  {
    title: '小数',
    dataIndex: 'demoNumber',
    key: 'demoNumber',
    ellipsis: true,
    minWidth: 120,
    resizable: true,
    align: 'right'
  },
  {
    title: '整数',
    dataIndex: 'demoInteger',
    key: 'demoInteger',
    ellipsis: true,
    minWidth: 120,
    resizable: true,
    align: 'right'
  },
  {
    title: '日期',
    dataIndex: 'demoDate',
    key: 'demoDate',
    ellipsis: true,
    minWidth: 120,
    resizable: true,
    align: 'center'
  },
  {
    title: '日期时间',
    dataIndex: 'demoDateTime',
    key: 'demoDateTime',
    ellipsis: true,
    minWidth: 120,
    resizable: true,
    align: 'center'
  },
  {
    title: '必填',
    dataIndex: 'demoNotnull',
    key: 'demoNotnull',
    ellipsis: true,
    minWidth: 120,
    resizable: true,
    customHeaderCell() {
      return {
        ['class']: 'required-table-title'
      };
    },
    align: 'left'
  },
  {
    title: '多行文本',
    dataIndex: 'demoTextarea',
    key: 'demoTextarea',
    ellipsis: true,
    minWidth: 120,
    resizable: true,
    align: 'left'
  },
  {
    title: '编码',
    dataIndex: 'demoCode',
    key: 'demoCode',
    ellipsis: true,
    minWidth: 120,
    resizable: true,
    align: 'left'
  },
  {
    title: '电话(正则)',
    dataIndex: 'demoPhone',
    key: 'demoPhone',
    ellipsis: true,
    minWidth: 120,
    resizable: true,
    align: 'left'
  },
  {
    title: '邮箱(正则)',
    dataIndex: 'demoEmail',
    key: 'demoEmail',
    ellipsis: true,
    minWidth: 120,
    resizable: true,
    align: 'left'
  },
  {
    title: '网址(正则)',
    dataIndex: 'demoWebsite',
    key: 'demoWebsite',
    ellipsis: true,
    minWidth: 120,
    resizable: true,
    align: 'left'
  },
  {
    title: '唯一值',
    dataIndex: 'demoUnique',
    key: 'demoUnique',
    ellipsis: true,
    minWidth: 120,
    resizable: true,
    customHeaderCell() {
      return {
        ['class']: 'required-table-title'
      };
    },
    align: 'left'
  },
  {
    title: '弹窗',
    dataIndex: 'demoModalSelect',
    key: 'demoModalSelect',
    ellipsis: true,
    minWidth: 120,
    resizable: true,
    align: 'left'
  },
  {
    title: '背景样式',
    dataIndex: 'demoBackgroundColor',
    key: 'demoBackgroundColor',
    ellipsis: true,
    minWidth: 120,
    resizable: true,
    align: 'left'
  },
  {
    title: '富文本',
    dataIndex: 'demoRichtext',
    key: 'demoRichtext',
    ellipsis: true,
    minWidth: 120,
    resizable: true,
    align: 'left'
  },
  {
    title: '测试文本',
    dataIndex: 'demoText2',
    key: 'demoText2',
    ellipsis: true,
    minWidth: 120,
    resizable: true,
    align: 'left'
  },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'action',
    width: 120,
    fixed: 'right',
    align: 'center'
  }
] as any[];
const queryForm = ref<DemoSubNestDto>({});
const queryParam = reactive({
  // 请求表格数据参数
  pageParameter: {
    page: 1, // 页数
    rows: proxy.$settings.table.pageSize || 20 // 每页条数
  },
  searchParams: {},
  keyWord: ref(''), // 快速查询数据
  sidx: null, // 排序字段
  sord: null // 排序方式: desc降序 asc升序
});
const demoSubNest = ref(null);
const list = ref([]); // 表格数据集合
const initialList = ref([]); // 记录每次刷新得到的表格的数据
const selectedRowKeys = ref([]); // 选中数据主键集合
const selectedRows = ref([]); // 选中行集合
const subLoading = ref(false); // 子表loading
const delLoading = ref(false);
const totalPage = ref(0);
const { lookupList } = useLookup(['PLATFORM_SEX', 'PLATFORM_CHECK_TYPE', 'PLATFORM_DEGREE', 'PLATFORM_FILE_SECRET_LEVEL']);
const validateRules = {
  demoUserId: [{ required: true, message: '用户列不能为空' }],
  secretLevel: [{ required: true, message: '密级列不能为空' }],
  demoNotnull: [{ required: true, message: '必填列不能为空' }],
  demoUnique: [{ required: true, message: '唯一值列不能为空' }]
}; // 必填列,便于保存和新增数据时校验
const deletedData = ref([]); // 前台删除数据的记录
const formatArrayKeys = ['demoCheckbox', 'demoSelectMultiple']; // 多选控件的值需要格式化数据

onMounted(() => {
  // 加载表格数据
  getList();
});
/** 查询数据  */
function getList() {
  selectedRowKeys.value = []; // 清空选中
  selectedRows.value = [];
  subLoading.value = true;
  queryForm.value.demoMainId = props.formId ? props.formId : '-1';
  queryParam.searchParams = queryForm.value;
  listDemoSubNestByPage(queryParam)
    .then((response) => {
      list.value = response.data.result;
      totalPage.value = response.data.pageParameter.totalCount;
      queryParam.pageParameter.page = response.data.pageParameter.page;
      subLoading.value = false;
      // 查询的初始数据,保存时做比对
      initialList.value = proxy.$lodash.cloneDeep(list.value);
    })
    .catch(() => {
      list.value = [];
      totalPage.value = 0;
      subLoading.value = false;
    });
}
/** 获取修改的数据 */
function getChangedData() {
  deletedData.value.forEach((item) => {
    item.operationType_ = 'delete';
  });
  const changedData = proxy.$getChangeRecords(list, initialList);
  return deletedData.value.concat(changedData);
}

/** 添加 */
function handleAdd() {
  const item = {
    id: `newLine${proxy.$uuid()}`,
    operationType_: 'insert',
    demoUserId: props.form.formStep1.demoUserId, // 代入主表数据示例
    demoUserIdAlias: props.form.formStep1.demoUserIdAlias, // 代入主表数据示例
    demoDeptId: '',
    demoRoleId: '',
    demoGroupId: '',
    demoPositionId: '',
    demoRadio: props.form.formStep1.demoRadio, // 代入主表数据示例
    demoRadioButton: '',
    demoCheckbox: [],
    demoSelect: undefined,
    demoSelectMultiple: [],
    secretLevel: undefined,
    demoSwitch: '',
    demoNumber: '',
    demoInteger: '',
    demoDate: null,
    demoDateTime: null,
    demoNotnull: '',
    demoTextarea: '',
    demoCode: '',
    demoPhone: '',
    demoEmail: '',
    demoWebsite: '',
    demoUnique: '',
    demoModalSelect: '',
    demoBackgroundColor: '',
    demoRichtext: '',
    demoText2: '',
    editable: true // true为编辑中, false为未编辑
  };
  const newData = [...list.value];
  // 数据校验
  if (!validateRecordData(newData)) {
    return;
  }
  // 其他列编辑状态修改为false
  newData.forEach((item) => {
    item.editable = false;
  });
  if (newData.length === queryParam.pageParameter.rows) {
    newData.pop();
  }
  newData.unshift(item);
  list.value = newData;
}
/** 编辑 */
function handleEdit(record) {
  record.editable = true;
  record.operationType_ = record.operationType_ || 'update';
  proxy.$formatValueToArray(record, formatArrayKeys);
  const newData = [...list.value];
  newData.forEach((item) => {
    if (item.id !== record.id) {
      item.editable = false;
    }
  });
  list.value = newData;
}

/** 删除处理逻辑 */
function handleDelete(ids, e) {
  if (e) {
    e.stopPropagation(); // 阻止冒泡
  }
  if (ids.length === 0) {
    proxy.$message.warning('请选择要删除的数据！');
    return;
  }
  let newData = [...list.value];
  const deletedItems = [];
  for (let i = 0; i < ids.length; i++) {
    if (ids[i].indexOf('newLine') === -1) {
      // 缓存删除的后台数据
      deletedItems.push(newData.find((item) => item.id === ids[i]));
    }
    newData = newData.filter((item) => item.id !== ids[i]);
  }
  // 清空表格选中项
  selectedRowKeys.value = [];
  selectedRows.value = [];
  // 前台刷新表格
  list.value = newData;
  deletedData.value = deletedData.value.concat(deletedItems);
}

/** 行点击事件 */
function customRow(record) {
  return {
    onClick: () => {
      handleEdit(record);
    }
  };
}
/** 勾选复选框时触发 */
function onSelectChange(rowKeys, rows) {
  selectedRowKeys.value = rowKeys;
  selectedRows.value = rows;
}
/** 表头排序 */
function handleTableChange(pagination, _filters, sorter) {
  queryParam.pageParameter.page = pagination.current;
  queryParam.pageParameter.rows = pagination.pageSize;
  if (proxy.$objIsNotBlank(sorter.field)) {
    queryParam.sidx = sorter.field;
    queryParam.sord = sorter.order === 'ascend' ? 'asc' : 'desc'; // 排序方式: desc降序 asc升序
  }
  getList();
}
/** 选人，选部门，选角色，选岗位，选组件的值变化事件 */
function changeCommonSelect(value, record, column) {
  record[`${column}Alias`] = value.names;
}
/** 控件变更事件 */
function changeControlValue({ value, record, column, lookupList }) {
  const labels = [];
  if (Array.isArray(value)) {
    // 多选处理
    for (let i = 0; i < value.length; i++) {
      // 从对应的通用代码中查询对应的label
      const target = lookupList.find((item) => value[i] === item.lookupCode);
      labels.push(target.lookupName);
    }
  } else {
    // 单选处理
    const target = lookupList.find((item) => value === item.lookupCode);
    labels.push(target.lookupName);
  }
  if (record) {
    record[`${column}Name`] = labels.join(',');
  }
}
/** 输入框的值失去焦点 */
function blurInput(e, record, column) {
  proxy.$validateData(e.target.value, column, validateRules, record); // 校验数据
}
/** 批量数据校验 */
function validateRecordData(records) {
  let flag = true;
  for (const index in records) {
    flag = proxy.$validateRecordData(records[index], validateRules, list.value, demoSubNest);
    if (!flag) {
      break;
    }
  }
  return flag;
}
/** 校验并执行回调函数 */
function validate(callback) {
  const changedData = proxy.$getChangeRecords(list, initialList);
  if (changedData && validateRecordData(changedData)) {
    // 校验通过
    if (callback) {
      return callback(true);
    }
  } else {
    // 校验未通过
    if (callback) {
      return callback(false);
    }
  }
  return true;
}
defineExpose({
  formStep2Ref,
  autoCode,
  validate,
  getChangedData
});
</script>
